<?php

require_once '../config_site.php';
require_once 'facebook.php';
require_once 'user.php';

$facebook = new Facebook(array(
            'appId' => APP_ID,
            'secret' => APP_SECRET,
            'cookie' => true
        ));

$session = $facebook->getSession();

if (!empty($session)) {
    # Active session, let's try getting the user id (getUser()) and user info (api->('/me'))
    
    try {
        $uid = $facebook->getUser();
    //    echo '<pre>';
        $user_info = $facebook->api('/me');
    } catch (FacebookApiException $e) {

//print_r($e);


    }

    if (!empty($user_info)) {
        $username = $user_info['name'];
        $user = new User();
        $userdata = $user->checkUser($uid, 'facebook', $user_info['username']);
        if(!empty($userdata)){
            session_start();
            $_SESSION['user']['id'] = $userdata['id'];
            $_SESSION['user']['oauth_id'] = $uid;
            $_SESSION['user']['oauth_provider'] = 'facebook';
            $_SESSION['user']['username'] = $user_info['username'];
            $_SESSION['user']['name'] = $user_info['name'];
            $_SESSION['user']['avatar'] = 'https://graph.facebook.com/'.$uid.'/picture';
            $_SESSION['user']['role'] = $userdata['role'];
            $_SESSION['user']['settings'] = array('character'=>$userdata['character'],
                                                  'items'=>$userdata['items'],
                                                  'weak'=>$userdata['weak'],
                                                  'sort_by'=>$userdata['sort_by']);
            header("Location: /");
        }
    } else {
        # For testing purposes, if there was an error, let's kill the script
        die("There was an error.");
    }
} else {
    # There's no active session, let's generate one
    $login_url = $facebook->getLoginUrl();
    header("Location: " . $login_url);
}
?>
